﻿using Youz.Common.Entity;
using Youz.Common.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace Youz.Common.BLL
{

    public class SMSBLL
    {
        public static ReturnMessage SendRegister(string phone, string memberAccount, string pwd)
        {
            string content = string.Format("欢迎使用华东期货交易所系统软件，您的帐号为：{0}， 密码为：{1}，请妥善保管。", memberAccount, pwd);
            return SMSBLL.SendSMS(phone, content);
        }

        public static ReturnMessage SendCode(string phone, string code, string msg)
        {
            string content = string.Format("您的验证码为{0}，您正在进行{1}", code, msg);
            return SMSBLL.SendSMS(phone, content);
        }

        public static ReturnMessage SendForgotPwd(string phone, string pwd)
        {
            string content = string.Format("由于您忘记了密码，我们为您重置密码为：{0}，请妥善保管。", pwd);
            return SMSBLL.SendSMS(phone, content);
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobiles">接收短信手机号</param>
        /// <param name="conteng">短信内容</param>
        /// <returns>AjaxResult对象</returns>
        public static ReturnMessage SendSMS(string mobiles, string content)
        {
            ReturnMessage result = new ReturnMessage();
            try
            {
                result = SendSMSAPI(mobiles, content);
                if (result.Result)
                {
                    result.Message = "尊敬的用户，短信已发送到您的手机，请注意查收";
                }
                else
                {
                    result.Message = "尊敬的用户，短信发送失败，如果手机号码无误请及时联系管理员";
                }
            }
            catch (Exception ex)
            {
                Utility.WriteErrorLog(ex);
            }
            return result;
        }


        private static ReturnMessage SendSMSAPI(string phone, string content)
        {
            string sign = "【华东期货】";

            ReturnMessage returnMsg = new ReturnMessage(false,"号码错误");
            if (phone.Substring(0, 2) == "86" && phone.Length == 13) //国内通道
            {
                string productid = "676767";
                phone = phone.Substring(2); //使用國內通道，去掉86
                string fmt = "productid={0}&username={1}&password={2}&mobile={3}&content={4}";
                string data = string.Format(fmt, new string[] { productid, ConfigParameters.AppKey, ConfigParameters.AppSecret, phone, content + sign });
                string result = WebRequestHelper.GetResponseTextPOST(ConfigParameters.SMSServer, data);                
                returnMsg.Result = result.Contains("1,") ? true : false;
                if (!returnMsg.Result)
                {
                    result = result.Contains("0,") ? "0" : result;
                    result = result.Contains("5,") ? "5" : result;
                    returnMsg.Message = ConvertResultZT(true, result);
                    Utility.WriteErrorLog("助通科技国内短信发送", "SendSMSAPI", returnMsg.Message);
                }
            }
            else //国际通道
            {
                string fmt = "src={0}&pwd={1}&ServiceID=SEND&dest={2}&msg={3}";
                string data = string.Format(fmt, new string[] { ConfigParameters.AppKey1, ConfigParameters.AppSecret1, phone, encodeHexStr(8, content + sign) });
                string result = WebRequestHelper.GetResponseTextPOST(ConfigParameters.SMSServer1, data);
                returnMsg.Result = result.Substring(0, 1) == "-" ? false : true;
                if (!returnMsg.Result)
                {
                    returnMsg.Message = ConvertResultISMS(result);
                    Utility.WriteErrorLog("信合瑞科技国际短信发送", "SendSMSAPI", returnMsg.Message);
                }
            }
            return returnMsg;
        }

        /// <summary>
        /// 返回值转换
        /// </summary>
        /// <param name="result">短信返回值</param>
        /// <returns>短信發送結果</returns>
        private static string ConvertResultZT(bool isGn, string key)
        {
            Dictionary<string, string> dicResult = new Dictionary<string, string>();
            if (isGn) //true 代表国内短信发送
            {
                dicResult.Add("-1", "用户名或者密码不正确");
                dicResult.Add("0", "发送短信失败");
                dicResult.Add("2", "余额不够");
                dicResult.Add("3", "扣费失败（请联系客服）");
                dicResult.Add("5", "短信定时成功");
                dicResult.Add("6", "有效号码为空");
                dicResult.Add("7", "短信内容为空");
                dicResult.Add("8", "无签名，必须，格式：【签名】");
                dicResult.Add("9", "没有Url提交权限");
                dicResult.Add("10", "发送号码过多,最多支持2000个号码");
                dicResult.Add("11", "产品ID异常或产品禁用");
                dicResult.Add("12", "参数异常");
                dicResult.Add("13", "30分种重复提交");
                dicResult.Add("14", "用户名或密码不正确，产品余额为0，禁止提交，联系客服");
                dicResult.Add("15", "Ip验证失败");
                dicResult.Add("19", "短信内容过长，最多支持500个");
                dicResult.Add("20", "定时时间不正确：格式：20130202120212(14位数字)");
            }
            else
            {
                dicResult.Add("-100", "系统错误");
                dicResult.Add("-101", "用户名或密码错");
                dicResult.Add("-102", "手机号码串长度非法");
                dicResult.Add("-103", "短信为空");
                dicResult.Add("-104", "授权余额不足");
                dicResult.Add("-105", "手机号码格式不正确");
                dicResult.Add("-106", "IP地址未绑定");
            }
            if (dicResult.ContainsKey(key))
            {
                return dicResult[key];
            }
            else
            {
                return "未知错误，请联系短信运营商";
            }
        }

        private static String encodeHexStr(int dataCoding, String realStr)
        {
            string strhex = "";
            try
            {
                Byte[] bytSource = null;
                if (dataCoding == 15)
                {
                    bytSource = Encoding.GetEncoding("GBK").GetBytes(realStr);
                }
                else if (dataCoding == 3)
                {
                    bytSource = Encoding.GetEncoding("ISO-8859-1").GetBytes(realStr);
                }
                else if (dataCoding == 8)
                {
                    bytSource = Encoding.BigEndianUnicode.GetBytes(realStr);
                }
                else
                {
                    bytSource = Encoding.ASCII.GetBytes(realStr);
                }
                for (int i = 0; i < bytSource.Length; i++)
                {
                    strhex = strhex + bytSource[i].ToString("X2");

                }
            }
            catch
            {
                return realStr;
            }
            return strhex;
        }

        /// <summary>
        /// 返回值转换
        /// </summary>
        /// <param name="result">短信返回值</param>
        /// <returns>短信發送結果</returns>
        private static string ConvertResultISMS(string key)
        {
            Dictionary<string, string> dicResult = new Dictionary<string, string>();
            dicResult.Add("-01", "系统维护中,请联系客服");
            dicResult.Add("-02", "当前帐号余额不足");
            dicResult.Add("-03", "帐号停止");
            dicResult.Add("-04", "目的号码运营商不在服务覆盖范围");
            dicResult.Add("-05", "目的手机号码数量超长（30/次，超30个请自行做循环）");
            dicResult.Add("-06", "用户或密码错误");
            dicResult.Add("-07", "目的号码不能为空");
            dicResult.Add("-08", "短信内容不能为空");
            dicResult.Add("-09", "源号码不能为空");
            dicResult.Add("-10", "DEST参数格式错误");
            dicResult.Add("-11", "用户名空");
            dicResult.Add("-12", "密码空");
            dicResult.Add("-13", "网络错误");
            dicResult.Add("-14", "内部错误");
            dicResult.Add("-15", "非法手机号码，手机号码格式不对");
            dicResult.Add("-16", "短信内容超长！（Unicode最大70个字符；Alphabet编码（英文编码）最大160个字符）");
            dicResult.Add("-17", "短信内容含有非法字符");
            dicResult.Add("-18", "目的手机号码限制");
            dicResult.Add("-19", "短信内容编码不正确（比如发中文、韩文、日文而用Alphabet编码方式）");
            if (dicResult.ContainsKey(key))
            {
                return dicResult[key];
            }
            else
            {
                return "未知错误，请联系短信运营商";
            }
        }
    }
}
